<template>
  <view class="search-box">
    <uni-search-bar :radius="100" @confirm="search" @input="input" :focus="true" cancelButton="none"></uni-search-bar>

    <view class="sugg-list" v-if="searchResults.length !== 0">
      <view class="sugg-item" v-for="(item, index) in searchResults" :key="index" @click="toDetail(item)">
        <view class="goods-name">{{item.goods_name}}</view>
        <uni-icons type="arrowright" size=16></uni-icons>
      </view>
    </view>

    <view class="history-list" v-else>
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size=17 @click="cleanHistory"></uni-icons>
      </view>
      <view class="history-item">
        <uni-tag v-for="(item, i) in historys" :key="i" :text="item" @click="toGoodsList(item)"></uni-tag>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        timer: null,
        kw: ',', //搜索关键词
        searchResults: [], //搜索结果列表
        historyList: []

      };
    },
    onLoad() {
      // 页面加载获取历史搜索关键词
      this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
    },
    computed: {
      // 解决搜索历史顺序问题：
      // 原来的historyList不做任何修改，定义一个计算属性
      // 注意，由于数组是引用类型，所以不能直接基于原数组调用reverse方法，以免修改原数组中元素的顺序
      // 而是应该新建一个内存无关的数组，在进行reverse反转
      historys() {
        return [...this.historyList].reverse()
      }
    },
    methods: {
      input(val) {
        // 用定时器解决输入防抖
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.kw = val
          // 根据搜索关键词-查询搜索建议列表
          this.getSearchList()
        }, 500)
      },
      async getSearchList() {
        if (this.kw.length == 0) {
          this.searchResults = []
          return
        } else {
          const {
            data
          } = await uni.$http.get('/api/public/v1/goods/qsearch', {
            query: this.kw
          })
          if (data.meta.status !== 200) return uni.$showMsg()
          this.searchResults = data.message
          // 搜索完成后保存搜索关键词
          this.saveSearchHistory()
        }
      },
      saveSearchHistory() {
        // this.historyList.push(this.kw) //顺序和去重
        // 历史关键词重复问题
        const set = new Set(this.historyList)
        set.delete(this.kw) //先删除再添加
        set.add(this.kw)

        this.historyList = Array.from(set)
        // 本地持久存储
        uni.setStorageSync('kw', JSON.stringify(this.historyList))
      },
      cleanHistory() {
        this.historyList = []
        uni.setStorageSync('kw', this.historyList)
      },
      toDetail(item) {
        uni.navigateTo({
          url: "/subpkg/goods_detail/goods_detail?goods_id=" + item.goods_id
        })
      },
      toGoodsList(kw) {
        console.log(kw);
        uni.navigateTo({
          url: "/subpkg/goods_list/goods_list?query=" + kw
        })
      }
    }
  }
</script>

<style lang="scss">
  // 修改uni组件背景色
  .uni-searchbar {
    background-color: #C00000;
  }

  .search-box {
    position: sticky; //头部吸顶效果
    top: 0;
    z-index: 999;
  }

  .sugg-list {
    padding: 0 10px;

    .sugg-item {
      display: flex;
      align-items: center; //纵向居中
      justify-content: space-between; //横向两边贴边

      font-size: 12px;
      padding: 12px 0;

      border-bottom: 1px solid #eee;

      .goods-name {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }

  }

  .history-list {
    padding: 0 5px;

    .history-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 40px;
      font-size: 14px;
      border-bottom: 1px solid #eee;
    }

    .history-item {
      display: flex;
      flex-wrap: wrap; //允许换行

      .uni-tag {
        margin-top: 5px;
        margin-right: 5px;
      }

    }
  }
</style>
